<template>
    <view>
        <view class="container">
            <view class='edit-container'>
                <view class="a-item">
                    <view class="icon">
                        <image class="img" src="/static/images/icon/receiver.png"></image>
                    </view>
                    <view class="input-wrap">
                        <input v-model="formData.name" cursor-spacing='100' class='a-input' placeholder='姓名'></input>
                    </view>
                </view>
                <view class="a-item">
                    <view class="icon">
                        <image class="img" src="/static/images/icon/mobile.png"></image>
                    </view>
                    <view class="input-wrap">
                        <input cursor-spacing='100' v-model="formData.mobile" class='a-input' type='number'
                            placeholder='手机号码'></input>
                    </view>
                </view>
                <view class="a-item">
                    <view class="icon">
                        <image class="img" src="/static/images/icon/position.png"></image>
                    </view>
                    <view class="input-wrap">
                        <input cursor-spacing='100' :value="full_region" @click="chooseRegion" class="a-input"
                            disabled="true" placeholder="选择省份、城市、区县" />
                        <view class="arrow"></view>
                    </view>
                </view>
                <view class="a-item">
                    <view class="icon">
                        <image class="img" src="/static/images/icon/address.png"></image>
                    </view>
                    <view class="input-wrap">
                        <input cursor-spacing='100' v-model="formData.address" class="a-input"
                            placeholder="详细地址, 如街道、小区或写字楼等" />
                    </view>
                </view>
            </view>
            <view class="default-wrap">
                <view class="text">设为默认地址</view>
                <!--这里用的 uview组件库的开关-->
                <u-switch class="switch" v-model="is_default"></u-switch>
            </view>
            <view class='btn-wrap' @click="saveAddress">
                <view class="btn active">保存</view>
            </view>
            <view class='delete-wrap' v-if="addressId">
                <view class='btn' @click="delAddress">删除</view>
            </view>
            <view class="region-select" v-if="regionShow">
                <view class="hd">
                    <view class="region-selected">
                        <!-- 渲染顶部 省市区 
                        如果item.id是0说明还没有被选择，就要有disabled的class； 如果每个的type刚好和regionType相同则激活，有selected名称
                        -->
                        <view class="item" @click="selectRegionType(item,index)"
                            :class="{ disabled:item.id===0, selected:regionType===index+1}"
                            v-for="(item,index) in selectRegionList" :key="index">
                            {{item.name}}
                        </view>
                    </view>
                    <view class="done" :class="{disabled:confirmDisabled}" @click="doneSelectRegion">确定</view>
                </view>
                <view class="bd">
                    <scroll-view scroll-y class="region-list">
                        <!-- 渲染地区数据-->
                        <view class="item" @click="selectRegion(item)" :class="{selected:item.selected}"
                            v-for="item in regionList" :key="item.id">{{item.name}}</view>
                    </scroll-view>
                </view>
            </view>
        </view>
        <view class="bg-mask" @click="cancelSelectRegion" v-if="regionShow"></view>
    </view>
</template>


<script>
    export default {
        data() {
            return {
                formData: {
                    name: '', // 姓名
                    mobile: '', // 手机号
                    address: '', // 详细地址信息
                    province_id: '', // 省份ID
                    city_id: '', // 城市ID
                    district_id: '', // 区县ID
                    is_default: 0 // (开关)是否默认
                },
                regionShow: false, // 是否展示地区的弹窗
                selectRegionList: [ // 用于渲染顶部位置信息
                    {
                        id: 0,
                        name: '省份',
                        parent_id: 1,
                        type: 1
                    },
                    {
                        id: 0,
                        name: '城市',
                        parent_id: 1,
                        type: 2
                    },
                    {
                        id: 0,
                        name: '区县',
                        parent_id: 1,
                        type: 3
                    }
                ],
                regionType: 1, // 1选择省份， 2选择城市， 3选择区县
                regionList: [], // 地址列表
                addressInfo: { // 记录省市县名称
                    province_name: '',
                    city_name: '',
                    district_name: ''
                },
                addressId: '' // 修改地址IDs
            };
        },
        computed: {
            //1.计算省市区是否有没有选择的，如果有，就禁用
            confirmDisabled() {
                return this.selectRegionList.some(item => item.id === 0)
            },
            //2.对地址的完整描述
            full_region() {
                return Object.values(this.addressInfo).join('')
            }
        },
        methods: {
            //1.打开地区弹窗
            chooseRegion() {
                //弹框打开
                this.regionShow = true
                //判断是否有选择地区
                if (this.formData.province_id > 0 && this.formData.city_id > 0 && this.formData.district_id > 0) {

                    this.selectRegionList[0].id = this.formData.province_id
                    this.selectRegionList[0].name = this.addressInfo.province_name
                    this.selectRegionList[0].parent_id = 1

                    this.selectRegionList[1].id = this.formData.city_id
                    this.selectRegionList[1].name = this.addressInfo.city_name
                    this.selectRegionList[1].parent_id = this.formData.province_id

                    this.selectRegionList[2].id = this.formData.district_id
                    this.selectRegionList[2].name = this.addressInfo.district_name
                    this.selectRegionList[2].parent_id = this.formData.city_id

                    //设置类型为3级（区）
                    this.regionType = 3
                    //拿到3级（区）的数据
                    this.getRegionList(this.formData.city_id)
                } else {
                    // 【情况1】：从未选择过但打开了(第一次)   
                    // 【情况2】：之前选择过，点击去了取消(注意了selectRegionList可能有残留数据)
                    this.selectRegionList = [{
                            id: 0,
                            name: '省份',
                            parent_id: 1,
                            type: 1
                        },
                        {
                            id: 0,
                            name: '城市',
                            parent_id: 1,
                            type: 2
                        },
                        {
                            id: 0,
                            name: '区县',
                            parent_id: 1,
                            type: 3
                        }
                    ]
                    //设置类型为1级
                    this.regionType = 1
                    // 获取1级省份数据
                    this.getRegionList(1)
                }
            },
            //2.关闭地区弹窗,
            cancelSelectRegion() {
                this.regionShow = false
                this.regionType = this.confirmDisabled ? 1 : 3
            },
            //3.获取地区数据的方法
            async getRegionList(regionId) {
                const res = await uni.$http.get('/region/list', {
                    params: {
                        parentId: regionId
                    }
                })

                //高亮显示 已经选择的地区
                this.regionList = res.map(item => {
                    if (this.regionType === item.type && this.selectRegionList[this.regionType - 1]
                        .id ===
                        item.id) {
                        item.selected = true
                    } else {
                        item.selected = false
                    }
                    return item
                })
            },
            //4.点击地区列表
            selectRegion(val) {
                //val是点击的对应的地区数据
                // (1).点击地区后，顶部显示的内容也要变化，splice(添加的位置，数量，添加的内容)
                this.selectRegionList.splice(val.type - 1, 1, val)
                // (2). 更换type类型，获取(切换到)下级列表
                if (this.regionType !== 3) {
                    this.regionType++ //type变化
                    this.getRegionList(val.id) //重新获取列表
                }
                //重置下级区域为空
                this.selectRegionList = this.selectRegionList.map((item, index) => {
                    if (index > val.type - 1) {
                        //重置
                        item.id = 0
                        item.name = index === 1 ? '城市' : '区县'
                        item.parent_id = 0
                    }
                    return item
                })

                //高亮显示 已经选择的地区
                this.regionList = this.regionList.map(item => {
                    if (this.regionType === item.type && this.selectRegionList[this.regionType - 1]
                        .id ===
                        item.id) {
                        item.selected = true
                    } else {
                        item.selected = false
                    }
                    return item
                })
            },
            //5.切换地区type
            selectRegionType(val, idx) {
                // console.log(val, idx);
                //判断有没有选,没选的话就不要跳转
                if (this.selectRegionList[idx].id === 0) return
                //高亮的项，点击没有效果
                if (val.type === this.regionType) return
                //有选择地区
                this.regionType = idx + 1
                //重新获取列表
                this.getRegionList(val.parent_id)
            },
            //6.点击地区弹窗的确定按钮
            doneSelectRegion() {
                //判断按钮的禁用
                if (this.confirmDisabled) return
                //存储地区Id
                this.formData.province_id = this.selectRegionList[0].id
                this.formData.city_id = this.selectRegionList[1].id
                this.formData.district_id = this.selectRegionList[2].id
                //收集选择对应的地区名称
                this.addressInfo.province_name = this.selectRegionList[0].name
                this.addressInfo.city_name = this.selectRegionList[1].name
                this.addressInfo.district_name = this.selectRegionList[2].name
                //关闭弹框
                this.regionShow = false
            },
            //7.保存地址
            async saveAddress() {
                //这里我们只判断有没有空的项没填
                let valueArr = Object.values(this.formData)
                if (valueArr.some(item => item === '')) return uni.showToast({
                    title: '有数据没填写',
                    icon: 'error'
                })
                //发请求提交
                await uni.$http.post('/address/saveAddress', this.formData)
                //提示成功
                uni.showToast({
                    title: this.addressId ? '修改成功' : '添加成功',
                    icon: 'success',
                    // duration: 300 //showToast提示显示的时长
                })
                //跳转
                setTimeout(() => {
                    uni.navigateBack() //因为是从别的页面进来的，保存之后返回之前的页面
                }, 300)
            },
            //8.修改地址信息并回显
            async getAddressInfo() {
                const res = await uni.$http.get('/address/addressDetail', {
                    params: {
                        id: this.addressId
                    }
                })
                // console.log(res);
                this.formData = res
                this.addressInfo.province_name = res.province_name
                this.addressInfo.city_name = res.city_name
                this.addressInfo.district_name = res.district_name
            },
            //9.删除地址
            async delAddress() {
                //弹出确认框
                const [err, res] = await uni.showModal({
                    content: '确定删除吗？'
                })
                //res里有取消和确认的信息
                //如果点击了取消，什么都不执行
                if (res.cancel) return
                //如果点击了确认,发送删除请求
                await uni.$http.post('/address/deleteAddress', {
                    id: this.addressId
                })
                //提示成功
                uni.showToast({
                    title:'删除成功',
                    icon:'success',
                    duration:300
                })
                //跳回之前的页面
                setTimeout(()=>{
                    uni.navigateBack()
                },300)
                
            }
        },
        //页面首次加载时触发，一个页面只触发一次（页面会缓存）
        onLoad(options) {
            // console.log(options); //携带id
            // 如果携带了id，说明是修改界面
            if (options.id) {
                //存储地址
                this.addressId = options.id
                //修改标题
                uni.setNavigationBarTitle({
                    title: '修改地址'
                })
                //获取数据回显
                this.getAddressInfo()
            }
        }
    }
</script>

<style lang="scss">
    page {
        min-height: 100%;
        background-color: #f8f8f8;
    }

    .container {
        min-height: 100%;
        /* align-items: stretch; */
        background: #f8f8f8;
        overflow-x: hidden;
        padding: 30rpx;
    }

    .edit-container {
        background: #fff;
        width: 100%;
        margin-bottom: 30rpx;
        border-radius: 10rpx;
        box-shadow: 2rpx 8rpx 18rpx #f1f1f1;
    }

    .a-item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-left: 30rpx;
    }

    .a-item .icon {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-right: 20rpx;
    }

    .a-item .icon .img {
        width: 36rpx;
        height: 36rpx;
    }

    .a-item .input-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        padding: 30rpx 30rpx 30rpx 0;
        border-bottom: 1rpx solid #f1f1f1;
    }

    .a-item:last-child .input-wrap {
        border-bottom: none;
    }

    .a-item .input-wrap .a-input {
        font-size: 28rpx;
        width: 100%;
    }

    .a-item .input-wrap .arrow {
        width: 10rpx;
        height: 10rpx;
        border-top: 4rpx solid #aaa;
        border-right: 4rpx solid #aaa;
        transform: rotate(45deg);
    }

    .a-input {
        font-size: 28rpx;
        width: 100%;
    }

    .confirm-box {
        width: 100%;
        height: 100rpx;
        position: fixed;
        bottom: 0;
        left: 0;
        /* border-top:1px solid #eee;  */
        background: linear-gradient(to right, #ff116a, #fe5b46);
        text-align: center;
        line-height: 100rpx;
        color: #fff;
        font-size: 32rpx;
    }

    .default-input {
        font-size: 28rpx;
        color: #233445;
        line-height: 60rpx;
        margin: 0 auto;
        width: 300rpx;
    }

    .region-select {
        width: 100%;
        height: 600rpx;
        background: #fff;
        position: fixed;
        z-index: 10;
        left: 0;
        bottom: 0;
    }

    .region-select .hd {
        height: 108rpx;
        width: 100%;
        border-bottom: 1px solid #f4f4f4;
        padding: 46rpx 30rpx 0 30rpx;
        box-sizing: border-box;
    }

    .region-select .region-selected {
        float: left;
        height: 60rpx;
        display: flex;
    }

    .region-select .region-selected .item {
        max-width: 140rpx;
        margin-right: 30rpx;
        text-align: left;
        line-height: 60rpx;
        height: 100%;
        color: #333;
        font-size: 28rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .region-select .region-selected .item.disabled {
        color: #999;
    }

    .region-select .region-selected .item.selected {
        color: #ff3456;
    }

    .region-select .done {
        float: right;
        height: 60rpx;
        width: 60rpx;
        border: none;
        background: #fff;
        line-height: 60rpx;
        text-align: center;
        color: #ff3456;
        font-size: 28rpx;
    }

    .region-select .done.disabled {
        color: #999;
    }

    .region-select .bd {
        height: 492rpx;
        width: 100%;
        padding: 0 30rpx;
    }

    .region-select .region-list {
        height: 492rpx;
    }

    .region-select .region-list .item {
        width: 100%;
        height: 104rpx;
        line-height: 104rpx;
        text-align: left;
        color: #333;
        font-size: 28rpx;
    }

    .region-select .region-list .item.selected {
        color: #ff3456;
    }

    .bg-mask {
        height: 100%;
        width: 100%;
        background: rgba(0, 0, 0, 0.4);
        position: fixed;
        top: 0;
        left: 0;
        z-index: 8;
    }

    .default-wrap {
        background: #fff;
        width: 100%;
        margin-bottom: 30rpx;
        border-radius: 10rpx;
        box-shadow: 2rpx 8rpx 18rpx #f1f1f1;
        padding: 30rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;
    }

    .default-wrap .text {
        font-size: 28rpx;
    }

    .btn-wrap {
        width: 100%;
        padding: 24rpx 0;
        /* position: fixed;
    bottom: 0;
    left: 0; */
        box-sizing: border-box;
    }

    .btn-wrap .btn {
        font-size: 28rpx;
        height: 100rpx;
        line-height: 100rpx;
        text-align: center;
        border-radius: 10rpx;
        width: 100%;
        color: #fff;
        background: #bbb;
        box-shadow: 0rpx 10rpx 20rpx #ccc;
    }

    .btn-wrap .btn.active {
        background: linear-gradient(to right, #ff3456, #ff347d);
        box-shadow: 0rpx 10rpx 20rpx #f1f1f1;
        color: #fff;
    }

    .delete-wrap {
        width: 100%;
        padding: 24rpx;
        /* position: fixed;
    bottom: 0;
    left: 0; */
        box-sizing: border-box;
    }

    .delete-wrap .btn {
        font-size: 28rpx;
        color: #5d6777;
        text-align: center;
    }
</style>
